<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { useMessage } from 'naive-ui';
import { $t } from '@/locales';
import { usePersistentCountdown } from '@/hooks/business/use-persistent-countdown';

interface Props {
  email: string;
}

interface Emits {
  (e: 'next', code: string): void;
  (e: 'resend'): void;
}

const { email } = defineProps<Props>();
const emit = defineEmits<Emits>();

const code = ref(['', '', '', '', '', '']);
const loading = ref(false);
const showDialog = ref(false);
const inputRefs = ref<any[]>([]);
const { countdown, startCountdown } = usePersistentCountdown('reset-password-verification-code');

const message = useMessage();

onMounted(() => {
  inputRefs.value[0]?.focus();
});

const handleVerify = async (): Promise<void> => {
  const codeString = code.value.join('');
  if (codeString.length !== 6) {
    message.error($t('common.verifyCodeLength'));
    return;
  }

  loading.value = true;
  try {
    emit('next', codeString);
  } catch (err) {
    message.error(err instanceof Error ? err.message : $t('page.resetPassword.failed'));
  } finally {
    loading.value = false;
  }
};

const handleInput = (index: number, value: string) => {
  const numericValue = value.replace(/[^0-9]/g, '');
  code.value[index] = numericValue;

  if (numericValue && index < 5) {
    inputRefs.value[index + 1]?.focus();
  }
};

const handleKeydown = (index: number, e: KeyboardEvent) => {
  if (e.key === 'Backspace' && !code.value[index] && index > 0) {
    code.value[index - 1] = '';
    inputRefs.value[index - 1]?.focus();
  }
};

const handleResend = async () => {
  showDialog.value = false;
  loading.value = true;
  try {
    emit('resend');
    startCountdown();
  } finally {
    loading.value = false;
  }
};
</script>

<template>
  <div class="code-step">
    <p class="mb-4 text-sm text-gray-600">
      {{ $t('page.resetPassword.codeSentTo') }}
      <span class="text-primary">{{ email }}</span>
    </p>

    <div class="mb-4 flex justify-center gap-2">
      <NInput
        v-for="(digit, index) in code"
        :key="index"
        :ref="el => (inputRefs[index] = el)"
        v-model:value="code[index]"
        type="text"
        size="large"
        class="w-12 text-center"
        placeholder=""
        maxlength="1"
        autocomplete="off"
        @input="value => handleInput(index, value)"
        @keydown="e => handleKeydown(index, e)"
      />
    </div>

    <NButton
      class="mt-4"
      type="primary"
      block
      :disabled="code.some(d => !d) || loading"
      :loading="loading"
      @click="handleVerify"
    >
      {{ $t('common.next') }}
    </NButton>

    <div class="mt-3 flex items-center justify-center">
      <NButton text :disabled="countdown > 0" @click="showDialog = true">
        {{ countdown > 0 ? $t('page.resetPassword.waitToResend', { countdown }) : $t('common.noCode') }}
      </NButton>
    </div>

    <NModal v-model:show="showDialog" preset="dialog" :title="$t('common.resend')">
      <template #default>
        <div class="text-gray-600">
          {{ $t('page.resetPassword.resendCodeDesc', { email: email }) }}
        </div>
      </template>
      <template #action>
        <NButton @click="showDialog = false">{{ $t('common.cancel') }}</NButton>
        <NButton type="primary" :loading="loading" @click="handleResend">
          {{ $t('common.resend') }}
        </NButton>
      </template>
    </NModal>
  </div>
</template>
